package com.kfpanda.search.index;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.io.IOException;

import javax.activation.MimetypesFileTypeMap;

import org.apache.log4j.Logger;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.kfpanda.search.index.file.FileDocumentFactory;

/**
 * <b>ClassName:<b> IndexFiles
 * <br><b>Description: <br>
 * 给文件建立索引。
 * @Author: kfpanda
 * @Date：2012-1-8 下午03:39:18
 * @ModifyUser：
 *
 */
@Scope("prototype")
@Service("indexFile")
public class IndexFile {
	
	private Logger logger = Logger.getLogger(IndexFile.class);
	private FileDocumentor fileDoc;
	
	/**
	 * <b>Description: <br>
	 * 递归遍历目录下的所有文件，对每个文件创建索引。
	 * @param writer
	 * @param file
	 * @throws IOException
	 * @Author: kfpanda
	 * @ModifyUser：kfpanda
	 * @Date：2012-1-8 下午04:09:25
	 */
	public void indexDocs(IndexWriter writer, File file) throws IOException {
		if (file.canRead()) {
			if (file.isDirectory()) {
				String[] files = file.list();
				files = files == null ? new String[0] : files;
				for (int i = 0; i < files.length; i++) {
					indexDocs(writer, new File(file, files[i]));
				}
			} else {
				this.indexDocument(writer, file);
			}
		}
	}
	
	/**
	 * <b>Description: <br>
	 * 给指定的文件创建索引。
	 * @param writer
	 * @param file
	 * @throws CorruptIndexException
	 * @throws IOException
	 * @Author: kfpanda
	 * @ModifyUser：kfpanda
	 * @Date：2012-1-8 下午04:09:25
	 */
	public void indexDocument(IndexWriter writer, File file) throws CorruptIndexException, IOException {
		if( file != null && file.isFile() && file.canRead() ){
			MimetypesFileTypeMap mimeTypeMap = new MimetypesFileTypeMap();
			String mimeType = mimeTypeMap.getContentType(file);
			fileDoc = FileDocumentFactory.createFileDocument(mimeType);
			if(fileDoc != null){
				if(logger.isDebugEnabled()){
					logger.debug(file.getAbsolutePath() + " index document create.");
				}
				writer.addDocument(fileDoc.document(file));
			}
		}
	}

}
